/**
 * 
 */
package com.gopay.bis.web.controller.ebank;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ceb.ebank.CebB2bMessage;

/**
 * @CebB2bServerRes.java
 * @author Ryan
 * @2013-12-3 下午4:39:39  www.gopay.com.cn Inc.All rights reserved.
 */
@Scope("prototype")
@Controller
public class CebB2bServerRes extends BankResBase{
    /** 分隔符 */
    private static final String separator = "\\~\\|\\~";
    private static Log logger = LogFactory.getLog(CebB2bServerRes.class);
    @RequestMapping(value = "/cebB2bServerRes")
    @Override
    protected ModelAndView execute(HttpServletRequest request, HttpServletResponse response) {
        logger.error("--------------- CebB2bServerRes bankback ---------------");
        String responseCode = request.getParameter("ResponseCode");
        String plain = request.getParameter("Plain");
		String signature = request.getParameter("Signature");
		//返回的明文或密文有一项不存在，直接返回错误页面。
       if( StringUtils.isEmpty(plain) || StringUtils.isEmpty(signature) || StringUtils.isEmpty(responseCode)){
    	   String viewName = bisConfig.get("BIS.NOTIFY.CASHIER.FORWARD.FAIL");
    	   ModelAndView mv = new ModelAndView(viewName);
    	   mv.addObject("errorCode", ProcCodeConstants.PROC_CODE_100E7023);
    	   return mv;
       }
       if("0000".equals(responseCode)){
    	   return super.execute(request, response);
       }else{
    	   String viewName = bisConfig.get("BIS.NOTIFY.CASHIER.FORWARD.FAIL");
    	   ModelAndView mv = new ModelAndView(viewName);
    	   mv.addObject("errorCode", ProcCodeConstants.PROC_CODE_100E7023);
    	   return mv;
       }
    }
    
    @Override
    protected BaseMessage buildMessage(HttpServletRequest request) {
        CebB2bMessage message = new CebB2bMessage();
        // 银行返回的信息
        message.setResponseCode(request.getParameter("ResponseCode"));
        message.setPlainMessage(request.getParameter("Plain"));   //支付响应明文
        message.setSignMessage(request.getParameter("Signature"));   //支付响应密文
        parsePlainMessage(message);
        message.setAmount(new BigDecimal(message.getTransAmt()));
        message.setBankOrderId(message.getOrderId());
		//银行业务产品01企业网银支付
		message.setBankBusProd(BisBankBusinessProd._01);
        message.setBank(BankConstants.BANK_LOGO_CEB);
        return message;
    }


    @Override
    protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
        OrderInfo orderInfo = new OrderInfo();
        CebB2bMessage message = (CebB2bMessage) result.getModel("message");
        orderInfo.setOrderId(message.getOrderId());
        orderInfo.setAmt(String.valueOf(message.getAmount().longValue()));
        orderInfo.setNotifyNum("1");
        orderInfo.setPayStatus("00");
        orderInfo.setRetCode("00");
        orderInfo.setRetMsg("");
        return orderInfo;
    }

    private void parsePlainMessage( CebB2bMessage cebMessage){
        // 根据分隔符拆分出各个返回参数
           String[] reqParameters = cebMessage.getPlainMessage().split(separator);    
           for (String param : reqParameters) {
               String[] paramCollection = param.split("=");
               {
                   if (paramCollection.length > 1) {
                       if (paramCollection[0].equals("transId")) {
                           cebMessage.setTransId(paramCollection[1]);// 交易代码
                           continue;
                       }
                       if (paramCollection[0].equals("originalTransId")) {
                           cebMessage.setOriginalTransId(paramCollection[1]);// 原交易代码
                           continue;
                       }
                       if (paramCollection[0].equals("orderId")) {
                           cebMessage.setOrderId(paramCollection[1]);// 订单号
                           continue;
                       }
                       if (paramCollection[0].equals("transSeqNo")) {
                           cebMessage.setTransSeqNo(paramCollection[1]);// 支付系统交易流水号
                           continue;
                       }
                       if (paramCollection[0].equals("merchantId")) {
                           cebMessage.setMerchantId(paramCollection[1]);// 商户ＩＤ
                           continue;
                       }
                       if (paramCollection[0].equals("transDateTime")) {
                           cebMessage.setTransDateTime(paramCollection[1]);// 交易时间
                           continue;
                       }
                       if (paramCollection[0].equals("ppDateTime")) {
                           cebMessage.setPpDateTime(paramCollection[1]);// 支付系统交易时间
                           continue;
                       }
                       if (paramCollection[0].equals("clearingDate")) {
                           cebMessage.setClearingDate(paramCollection[1]);// 清算日期
                           continue;
                       }
                       if (paramCollection[0].equals("transAmt")) {
                           cebMessage.setTransAmt(paramCollection[1]);// 交易金额
                           continue;
                       }
                       if (paramCollection[0].equals("transAmt1")) {
                           cebMessage.setTransAmt1(paramCollection[1]);// 已退货金额
                           continue;
                       }
                       if (paramCollection[0].equals("feeAmt")) {
                           cebMessage.setFeeAmt(paramCollection[1]);// 手续费金额
                           continue;
                       }
                       if (paramCollection[0].equals("transStatus")) {
                           cebMessage.setTransStatus(paramCollection[1]);// 交易状态
                           continue;
                       }
                       if (paramCollection[0].equals("respCode")) {
                           cebMessage.setRespCode(paramCollection[1]);// 响应代码
                           continue;
                       }
                       if (paramCollection[0].equals("payAcctType")) {
                           cebMessage.setPayAcctType(paramCollection[1]);// 客户账户类型
                           continue;
                       }
                   } else {
                       if (paramCollection[0].equals("transId")) {
                           cebMessage.setTransId(null);// 交易代码
                           continue;
                       }
                       if (paramCollection[0].equals("originalTransId")) {
                           cebMessage.setOriginalTransId(null);// 原交易代码
                           continue;
                       }
                       if (paramCollection[0].equals("orderId")) {
                           cebMessage.setOrderId(null);// 订单号
                           continue;
                       }
                       if (paramCollection[0].equals("transSeqNo")) {
                           cebMessage.setTransSeqNo(null);// 支付系统交易流水号
                           continue;
                       }
                       if (paramCollection[0].equals("merchantId")) {
                           cebMessage.setMerchantId(null);// 商户ＩＤ
                           continue;
                       }
                       if (paramCollection[0].equals("transDateTime")) {
                           cebMessage.setTransDateTime(null);// 交易时间
                           continue;
                       }
                       if (paramCollection[0].equals("ppDateTime")) {
                           cebMessage.setPpDateTime(null);// 支付系统交易时间
                           continue;
                       }
                       if (paramCollection[0].equals("clearingDate")) {
                           cebMessage.setClearingDate(null);// 清算日期
                           continue;
                       }
                       if (paramCollection[0].equals("transAmt")) {
                           cebMessage.setTransAmt(null);// 交易金额
                           continue;
                       }
                       if (paramCollection[0].equals("transAmt1")) {
                           cebMessage.setTransAmt1(null);// 已退货金额
                           continue;
                       }
                       if (paramCollection[0].equals("feeAmt")) {
                           cebMessage.setFeeAmt(null);// 手续费金额
                           continue;
                       }
                       if (paramCollection[0].equals("transStatus")) {
                           cebMessage.setTransStatus(null);// 交易状态
                           continue;
                       }
                       if (paramCollection[0].equals("respCode")) {
                           cebMessage.setRespCode(null);// 响应代码
                           continue;
                       }
                       if (paramCollection[0].equals("payAcctType")) {
                           cebMessage.setPayAcctType(null);// 客户账户类型
                           continue;
                       }
                   }
               }
           }
           
       }

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		 String responseCode = request.getParameter("ResponseCode");
	        String plain = request.getParameter("Plain");
			String signature = request.getParameter("Signature");
			
			//返回的明文或密文有一项不存在，直接返回错误页面。
	       if( StringUtils.isEmpty(plain) || StringUtils.isEmpty(signature) || StringUtils.isEmpty(responseCode)){
	    	  return false;
	       }
	       if("0000".equals(responseCode)){
	    	  return true;
	       }else{
	    	  return false;
	       }
	}
}
